<template>
  <div class="ui-automation-page">
    <el-tabs v-model="activeTab" class="main-tabs compact-tabs">
      <!-- 脚本编辑器 -->
      <el-tab-pane label="脚本编辑器" name="scripts">
        <div class="unified-interface-layout">
          <!-- 左侧：脚本列表 -->
          <div class="interface-sidebar">
            <div class="sidebar-header">
              <div class="search-filters">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索脚本..."
                  size="small"
                  style="width: 160px"
                  @input="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                
                <el-select
                  v-model="filterStatus"
                  placeholder="状态"
                  clearable
                  size="small"
                  style="width: 80px"
                  @change="loadScripts"
                >
                  <el-option label="草稿" value="draft" />
                  <el-option label="激活" value="active" />
                  <el-option label="停用" value="inactive" />
                </el-select>
    </div>

              <div class="header-actions">
                <el-button type="primary" size="small" @click="showCreateScriptForm">
                <el-icon><Plus /></el-icon>
                  新建
              </el-button>
            </div>
            </div>

            <div class="interface-list">
              <div 
                v-for="script in scripts" 
                :key="script.id"
                class="interface-item"
                :class="{ active: currentScript?.id === script.id }"
                @click="selectScript(script)"
              >
                <div class="interface-header">
                  <el-tag :type="getStatusTagType(script.status)" size="small">
                    {{ getStatusText(script.status) }}
                  </el-tag>
                  <span class="interface-name">{{ script.name }}</span>
          </div>
                <div class="interface-url">{{ script.description || '无描述' }}</div>
                <div class="interface-meta">
                  <span v-if="script.requirement_title" class="category">{{ script.requirement_title }}</span>
                  <span class="created-time">{{ formatDate(script.updated_at) }}</span>
                </div>
              </div>
            </div>

            <div class="pagination-small">
              <el-pagination
                v-model:current-page="scriptsPagination.page"
                v-model:page-size="scriptsPagination.size"
                :page-sizes="[10, 20, 50]"
                :total="scriptsPagination.total"
                layout="prev, pager, next"
                size="small"
                @size-change="loadScripts"
                @current-change="loadScripts"
              />
            </div>
          </div>

          <!-- 右侧：脚本编辑器 -->
          <div class="interface-editor">
            <!-- 新建脚本模式 -->
            <div v-if="showCreateScript" class="create-form">
              <div class="form-header">
                <h3>新建脚本</h3>
                <el-button size="small" @click="cancelCreateScript">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
              </div>
              <div class="form-content">
                <el-form :model="newScript" label-width="100px" size="small">
                  <el-form-item label="脚本名称" required>
                    <el-input v-model="newScript.name" placeholder="请输入脚本名称" />
                  </el-form-item>
                  <el-form-item label="描述">
                    <el-input v-model="newScript.description" type="textarea" placeholder="脚本描述" />
                  </el-form-item>
                  <el-form-item label="关联需求">
                    <el-select v-model="newScript.requirement_id" placeholder="选择需求" style="width: 100%">
                      <el-option 
                        v-for="req in requirements" 
                        :key="req.id" 
                        :label="req.title" 
                        :value="req.id" 
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="状态">
                    <el-select v-model="newScript.status" placeholder="选择状态" style="width: 100%">
                      <el-option label="草稿" value="draft" />
                      <el-option label="激活" value="active" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="saveNewScript">保存</el-button>
                    <el-button @click="cancelCreateScript">取消</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            
            <!-- 脚本编辑器 -->
            <div v-else-if="currentScript" class="script-editor">
              <div class="editor-header">
                <div class="script-title">
                  <span class="name">{{ currentScript.name }}</span>
                  <el-tag :type="getStatusTagType(currentScript.status)" size="small">
                    {{ getStatusText(currentScript.status) }}
                  </el-tag>
                </div>
                <div class="actions">
                  <el-button size="small" @click="saveScript" :loading="saving">
                    <el-icon><Document /></el-icon>
                    保存
                  </el-button>
                  <el-button size="small" @click="validateYaml">
                    <el-icon><CircleCheck /></el-icon>
                    验证
                  </el-button>
                  <el-button size="small" type="info" @click="showExecutionOptionsDialog">
                    <el-icon><Setting /></el-icon>
                    执行选项
                  </el-button>
                  <el-button size="small" type="success" @click="executeCurrentScript">
                    <el-icon><VideoPlay /></el-icon>
                    执行
                  </el-button>
                  <el-button size="small" @click="showGenerateDialog">
                    <el-icon><Star /></el-icon>
                    AI生成
                  </el-button>
                  <el-button size="small" @click="showHelpDialog">
                    <el-icon><QuestionFilled /></el-icon>
                    语法帮助
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteCurrentScript">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>

              <!-- YAML编辑器 -->
              <div class="yaml-editor-container">

                <div class="yaml-editor-wrapper">
                  <div class="line-numbers" ref="lineNumbers">
                    <div v-for="line in lineCount" :key="line" class="line-number">
                      {{ line }}
                    </div>
                  </div>
                  <div class="code-area">
                    <pre 
                      ref="yamlHighlight" 
                      class="yaml-highlight"
                      v-html="highlightedYaml"
                      @scroll="syncScroll"
                    ></pre>
                    <textarea
                      v-model="currentYamlContent"
                      ref="yamlTextarea"
                      class="yaml-textarea"
                      placeholder="请输入Midscene YAML脚本内容..."
                      @input="handleYamlChange"
                      @scroll="syncScroll"
                    ></textarea>
                  </div>
                </div>
              </div>




            </div>
            
            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="请选择一个脚本进行编辑或点击新建按钮创建脚本" />
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 执行报告 -->
      <el-tab-pane label="执行报告" name="executions">
        <ExecutionReportsView />
      </el-tab-pane>

      <!-- 批量执行 -->
      <el-tab-pane label="批量执行" name="batches">
        <BatchExecutionView 
          :scripts="scripts"
          @view-detail="viewBatch"
          @execute-batch="executeBatch"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 对话框组件 -->
    <YamlGenerateDialog
      v-model:visible="generateDialogVisible"
      :requirement-id="currentScript?.requirement_id"
      @generated="handleYamlGenerated"
    />

    <YamlHelpDialog v-model:visible="helpDialogVisible" />

    <ExecutionDetailDialog
      v-model:visible="executionDetailVisible"
      :execution="currentExecution"
    />



    <!-- 执行选项配置对话框 -->
    <el-dialog
      v-model="executionOptionsVisible"
      title="执行选项配置"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form label-width="120px">
        <!-- 基础执行选项 -->
        <el-divider content-position="left">基础选项</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="并发数量">
              <el-input-number v-model="executionOptions.concurrent" :min="1" :max="10" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="汇总报告">
              <el-input v-model="executionOptions.summary" placeholder="报告文件路径" />
            </el-form-item>
      </el-col>
    </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item>
              <el-checkbox v-model="executionOptions.continueOnError">错误时继续</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-checkbox v-model="executionOptions.shareBrowserContext">共享浏览器上下文</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 浏览器选项 -->
        <el-divider content-position="left">浏览器选项</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item>
              <el-checkbox v-model="executionOptions.headed">显示浏览器</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-checkbox v-model="executionOptions.keepWindow">保持窗口(默认)</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配置文件">
              <el-input v-model="executionOptions.config" placeholder="配置文件路径" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- Web选项 -->
        <el-divider content-position="left">Web选项</el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="用户代理">
              <el-input v-model="executionOptions.userAgent" placeholder="自定义User Agent" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="视口宽度">
              <el-input-number v-model="executionOptions.viewportWidth" :min="320" :max="2560" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="视口高度">
              <el-input-number v-model="executionOptions.viewportHeight" :min="240" :max="1440" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="Android设备ID">
              <el-input v-model="executionOptions.androidDeviceId" placeholder="Android设备ID" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 环境变量选项 -->
        <el-divider content-position="left">环境变量选项</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item>
              <el-checkbox v-model="executionOptions.dotenvDebug">Dotenv调试</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-checkbox v-model="executionOptions.dotenvOverride">覆盖环境变量</el-checkbox>
            </el-form-item>
      </el-col>
    </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="executionOptionsVisible = false">取消</el-button>
          <el-button type="primary" @click="executionOptionsVisible = false">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 悬浮执行输出框 -->
    <div 
      v-if="isExecuting || executionOutput" 
      class="floating-execution-output"
      :style="{ 
        width: outputWidth + 'px',
        height: outputHeight + 'px',
        right: outputPosition.x + 'px',
        bottom: outputPosition.y + 'px'
      }"
    >
      <div class="output-header" @mousedown="startDrag">
        <span class="output-title">
          <el-icon><VideoPlay /></el-icon>
          执行输出
        </span>
        <div class="output-actions" @mousedown.stop>
          <el-button 
            v-if="isExecuting && currentExecutionId" 
            size="small" 
            type="warning" 
            @click="stopExecution"
            :loading="stopping"
          >
            <el-icon><Close /></el-icon>
            终止
          </el-button>
          <el-button v-if="!isExecuting" size="small" @click="closeExecutionOutput">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
        </div>
      </div>
      <div 
        ref="outputContent"
        class="output-content" 
      >
        <pre v-if="executionOutput" class="output-text">{{ executionOutput }}</pre>
        <div v-if="isExecuting" class="executing-status">
          <el-icon class="is-loading"><Loading /></el-icon>
          正在执行脚本...
        </div>
      </div>
      <div 
        class="resize-handle"
        @mousedown="startResize"
      ></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import hljs from 'highlight.js/lib/core'
import yaml from 'highlight.js/lib/languages/yaml'
import 'highlight.js/styles/github.css'
import { 
  Document, VideoPlay, CircleCheck, Search, Plus, 
  Star, QuestionFilled, Delete, Close, Loading, Setting
} from '@element-plus/icons-vue'
import {
  getUiAutomationScripts,
  createUiAutomationScript,
  updateUiAutomationScript,
  deleteUiAutomationScript,
  executeUiAutomationScript,
  stopUiAutomationExecution,
  validateYamlScript
} from '../api/uiAutomation'
import { requirementsApi } from '../api/requirements'
import YamlGenerateDialog from './components/YamlGenerateDialog.vue'
import YamlHelpDialog from './components/YamlHelpDialog.vue'
import ExecutionDetailDialog from './components/ExecutionDetailDialog.vue'

import ExecutionReportsView from './components/ExecutionReportsView.vue'
import BatchExecutionView from './components/BatchExecutionView.vue'

// 当前激活的标签页
const activeTab = ref('scripts')

// ==================== 脚本管理 ====================
const scripts = ref([])
const scriptsLoading = ref(false)
const currentScript = ref(null)
const searchKeyword = ref('')
const filterStatus = ref('')
const scriptsPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 脚本编辑相关
const currentYamlContent = ref('')
const saving = ref(false)
const activeCollapse = ref(['options'])

// 执行控制相关
const currentExecutionId = ref(null)
const stopping = ref(false)
const yamlHighlight = ref(null)
const yamlTextarea = ref(null)
const lineNumbers = ref(null)
const highlightedYaml = ref('')
const lineCount = ref(1)

// 执行选项
const executionOptions = reactive({
  // 执行控制选项
  concurrent: 1,
  continueOnError: false,
  shareBrowserContext: false,
  summary: '',
  
  // 浏览器选项
  headed: false,
  keepWindow: true,
  
  // 配置文件
  config: '',
  
  // Web选项
  userAgent: '',
  viewportWidth: 1280,
  viewportHeight: 720,
  
  // Android选项
  androidDeviceId: '',
  
  // 环境变量选项
  dotenvDebug: false,
  dotenvOverride: false
})

// 新建脚本相关
const showCreateScript = ref(false)
const newScript = reactive({
  name: '',
  description: '',
  requirement_id: null,
  status: 'draft',
  yaml_content: ''
})

// 需求列表
const requirements = ref([])

// 对话框状态
const generateDialogVisible = ref(false)
const helpDialogVisible = ref(false)
const executionDetailVisible = ref(false)
const executionOptionsVisible = ref(false)
const currentExecution = ref(null)

// 执行输出状态 - 为每个脚本单独存储
const scriptExecutionStates = ref(new Map()) // 存储每个脚本的执行状态
const executionOutput = ref('')
const isExecuting = ref(false)
const outputHeight = ref(300)
const outputWidth = ref(600)
const outputContent = ref(null)
const isResizing = ref(false)
const isDragging = ref(false)

// 悬浮框位置
const outputPosition = ref({ x: 20, y: 20 })

// 调试：初始显示一些内容
// executionOutput.value = '[测试] 输出框已初始化，现在可以看到执行输出了'

// ==================== 方法定义 ====================

// 加载脚本列表
const loadScripts = async () => {
  scriptsLoading.value = true
  try {
    const params = {
      page: scriptsPagination.page,
      size: scriptsPagination.size,
      keyword: searchKeyword.value,
      status: filterStatus.value
    }
    const response = await getUiAutomationScripts(params)
    if (response && response.data) {
      scripts.value = Array.isArray(response.data.items) ? response.data.items : []
      scriptsPagination.total = response.data.total || 0
    } else {
      scripts.value = []
      scriptsPagination.total = 0
    }
  } catch (error) {
    ElMessage.error('加载脚本列表失败')
    scripts.value = []
    scriptsPagination.total = 0
  } finally {
    scriptsLoading.value = false
  }
}

// 加载需求列表
const loadRequirements = async () => {
  try {
    const response = await requirementsApi.getRequirements({ page: 1, size: 100 })
    if (response && response.data) {
      requirements.value = Array.isArray(response.data.items) ? response.data.items : []
    }
  } catch (error) {
    console.error('加载需求列表失败:', error)
    // 如果是认证错误，静默处理，不显示错误消息
    if (error.response?.status !== 401) {
      ElMessage.error('加载需求列表失败')
    }
  }
}

// 选择脚本
const selectScript = (script) => {
  // 保存当前脚本的执行状态
  if (currentScript.value?.id) {
    saveCurrentExecutionState()
  }
  
  currentScript.value = script
  updateEditorContent(script.yaml_content || '')
  showCreateScript.value = false // 关闭新建表单
  
  // 恢复选中脚本的执行状态
  restoreExecutionState(script.id)
}

// 显示创建脚本表单
const showCreateScriptForm = () => {
  // 保存当前脚本的执行状态
  if (currentScript.value?.id) {
    saveCurrentExecutionState()
  }
  
  showCreateScript.value = true
  currentScript.value = null // 清除选中状态
  
  // 切换到新建模式时清空执行输出
  executionOutput.value = ''
  isExecuting.value = false
  
  // 重置表单
  Object.assign(newScript, {
    name: '',
    description: '',
    requirement_id: null,
    status: 'draft',
    yaml_content: ''
  })
}

// 取消创建脚本
const cancelCreateScript = () => {
  showCreateScript.value = false
  // 取消创建时清空执行输出
  executionOutput.value = ''
  isExecuting.value = false
}

// 保存新脚本
const saveNewScript = async () => {
  try {
    const response = await createUiAutomationScript(newScript)
    if (response && response.data) {
      ElMessage.success('脚本创建成功')
      showCreateScript.value = false
      const newScriptData = response.data
      await loadScripts()
      // 选中新创建的脚本：从新加载的列表中找到对应的脚本
      const scriptInList = scripts.value.find(script => script.id === newScriptData.id)
      if (scriptInList) {
        currentScript.value = scriptInList
        currentYamlContent.value = scriptInList.yaml_content || ''
      }
    }
  } catch (error) {
    console.error('创建脚本失败:', error)
    ElMessage.error('创建脚本失败')
  }
}

// 保存脚本
const saveScript = async () => {
  if (!currentScript.value) return
  
  if (!currentScript.value.id) {
    ElMessage.warning('脚本ID无效，无法保存')
    return
  }
  
  saving.value = true
  try {
    const updateData = {
      yaml_content: currentYamlContent.value
    }
    
    console.log('保存脚本ID:', currentScript.value.id, '更新数据:', updateData)
    const response = await updateUiAutomationScript(currentScript.value.id, updateData)
    if (response && response.data) {
      ElMessage.success('脚本保存成功')
      // 更新当前脚本数据
      const updatedScript = response.data
      // 重新加载脚本列表以更新显示
      await loadScripts()
      // 恢复选中状态：从新加载的列表中找到对应的脚本并重新选中
      const scriptInList = scripts.value.find(script => script.id === updatedScript.id)
      if (scriptInList) {
        currentScript.value = scriptInList
        currentYamlContent.value = scriptInList.yaml_content || ''
      }
    }
  } catch (error) {
    console.error('保存脚本失败:', error)
    ElMessage.error('保存脚本失败')
  } finally {
    saving.value = false
  }
}

// 验证YAML
const validateYaml = async () => {
  if (!currentYamlContent.value.trim()) {
    ElMessage.warning('请输入YAML内容')
    return
  }
  
  try {
    const response = await validateYamlScript({ yaml_content: currentYamlContent.value })
    if (response && response.data) {
      if (response.data.valid) {
        ElMessage.success('YAML格式验证通过')
      } else {
        ElMessage.error(`YAML格式错误: ${response.data.error}`)
      }
    }
  } catch (error) {
    console.error('验证YAML失败:', error)
    ElMessage.error('验证YAML失败')
  }
}



// 删除当前脚本
const deleteCurrentScript = async () => {
  if (!currentScript.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除脚本 "${currentScript.value.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteUiAutomationScript(currentScript.value.id)
    ElMessage.success('删除成功')
    currentScript.value = null
    currentYamlContent.value = ''
    loadScripts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理搜索
const handleSearch = () => {
  scriptsPagination.page = 1
  loadScripts()
}

// 初始化highlight.js
hljs.registerLanguage('yaml', yaml)

// 处理YAML内容变化
const handleYamlChange = () => {
  updateHighlight()
}

// 更新高亮显示和行号
const updateHighlight = () => {
  const content = currentYamlContent.value || ''
  
  // 计算行数
  const lines = content.split('\n')
  lineCount.value = Math.max(1, lines.length)
  
  // 更新语法高亮
  if (content.trim()) {
    try {
      const highlighted = hljs.highlight(content, { language: 'yaml' }).value
      highlightedYaml.value = highlighted
    } catch (error) {
      highlightedYaml.value = content
    }
  } else {
    highlightedYaml.value = ''
  }
}

// 同步滚动
const syncScroll = () => {
  if (yamlTextarea.value && yamlHighlight.value && lineNumbers.value) {
    yamlHighlight.value.scrollTop = yamlTextarea.value.scrollTop
    yamlHighlight.value.scrollLeft = yamlTextarea.value.scrollLeft
    lineNumbers.value.scrollTop = yamlTextarea.value.scrollTop
  }
}

// 更新编辑器内容
const updateEditorContent = (content) => {
  currentYamlContent.value = content
  nextTick(() => {
    updateHighlight()
  })
}

// 执行当前脚本
const executeCurrentScript = async () => {
  if (!currentScript.value) {
    ElMessage.warning('请选择要执行的脚本')
    return
  }
  
  if (!currentScript.value.id) {
    ElMessage.warning('脚本ID无效，请重新选择脚本')
    return
  }
  
  try {
    // 先保存脚本
    await saveScript()
    
    // 再次验证脚本ID（防止保存过程中出现问题）
    if (!currentScript.value || !currentScript.value.id) {
      ElMessage.error('脚本ID无效，无法执行')
      return
    }
    
    // 清空之前的输出并设置执行状态
    executionOutput.value = ''
    isExecuting.value = true
    
    // 添加执行开始信息
    appendExecutionOutput(`[${new Date().toLocaleTimeString()}] 开始执行脚本: ${currentScript.value.name}`)
    appendExecutionOutput(`[${new Date().toLocaleTimeString()}] 脚本ID: ${currentScript.value.id}`)
    appendExecutionOutput(`[${new Date().toLocaleTimeString()}] 执行选项: ${JSON.stringify(executionOptions, null, 2)}`)
    appendExecutionOutput('')
    
    // 启动脚本执行
    ElMessage.info('正在启动脚本执行...')
    console.log('执行脚本ID:', currentScript.value.id, '执行选项:', executionOptions)
    
    appendExecutionOutput('发起API调用...')
    const response = await executeUiAutomationScript(currentScript.value.id, executionOptions)
    console.log('API响应:', response)
    
    if (response && response.data && response.data.success) {
      ElMessage.success('脚本执行已启动')
      appendExecutionOutput(`[${new Date().toLocaleTimeString()}] 脚本执行已启动`)
      
      if (response.data.data && response.data.data.execution_id) {
        appendExecutionOutput(`执行ID: ${response.data.data.execution_id}`)
        appendExecutionOutput('正在建立实时连接...')
        appendExecutionOutput('')
        
        // 启动SSE实时接收执行输出
        startSSEConnection(response.data.data.execution_id)
      }
    } else {
      ElMessage.error(response?.data?.message || '脚本启动失败')
      appendExecutionOutput(`[${new Date().toLocaleTimeString()}] 脚本启动失败`)
      isExecuting.value = false
    }
  } catch (error) {
    console.error('执行脚本失败:', error)
    ElMessage.error(`执行脚本失败: ${error.message || error}`)
    isExecuting.value = false
    appendExecutionOutput(`[${new Date().toLocaleTimeString()}] 错误: ${error.message || error}`)
    
    // 详细错误信息
    if (error.response) {
      appendExecutionOutput(`HTTP状态: ${error.response.status}`)
      appendExecutionOutput(`响应数据: ${JSON.stringify(error.response.data)}`)
    }
  }
}

// 保存当前脚本的执行状态
const saveCurrentExecutionState = () => {
  if (!currentScript.value?.id) return
  
  scriptExecutionStates.value.set(currentScript.value.id, {
    output: executionOutput.value,
    isExecuting: isExecuting.value,
    height: outputHeight.value,
    width: outputWidth.value,
    position: { ...outputPosition.value }
  })
}

// 恢复脚本的执行状态
const restoreExecutionState = (scriptId) => {
  const state = scriptExecutionStates.value.get(scriptId)
  if (state) {
    executionOutput.value = state.output
    isExecuting.value = state.isExecuting
    outputHeight.value = state.height
    outputWidth.value = state.width
    outputPosition.value = { ...state.position }
  } else {
    // 没有保存的状态，清空
    executionOutput.value = ''
    isExecuting.value = false
    outputHeight.value = 300
    outputWidth.value = 600
    outputPosition.value = { x: 20, y: 20 }
  }
}

// 关闭执行输出
const closeExecutionOutput = () => {
  executionOutput.value = ''
  isExecuting.value = false
  
  // 关闭SSE连接
  closeSSEConnection()
  
  // 同时清除当前脚本的保存状态
  if (currentScript.value?.id) {
    scriptExecutionStates.value.delete(currentScript.value.id)
  }
}

// 添加执行输出内容
const appendExecutionOutput = (text) => {
  executionOutput.value += text + '\n'
}

// 开始拖拽悬浮框
const startDrag = (event) => {
  isDragging.value = true
  const startX = event.clientX
  const startY = event.clientY
  const startPosX = outputPosition.value.x
  const startPosY = outputPosition.value.y

  const handleMouseMove = (moveEvent) => {
    if (!isDragging.value) return
    
    const deltaX = startX - moveEvent.clientX
    const deltaY = startY - moveEvent.clientY
    
    // 计算新位置，确保不超出视口
    const newX = Math.max(0, Math.min(window.innerWidth - outputWidth.value, startPosX + deltaX))
    const newY = Math.max(0, Math.min(window.innerHeight - outputHeight.value, startPosY + deltaY))
    
    outputPosition.value = { x: newX, y: newY }
  }

  const handleMouseUp = () => {
    isDragging.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    document.body.style.cursor = ''
    document.body.style.userSelect = ''
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  document.body.style.cursor = 'move'
  document.body.style.userSelect = 'none'
  event.preventDefault()
}

// SSE连接管理
let currentEventSource = null

// 启动SSE连接
const startSSEConnection = (executionId) => {
  // 保存执行ID
  currentExecutionId.value = executionId
  
  // 关闭之前的连接
  if (currentEventSource) {
    currentEventSource.close()
  }
  
  // 获取token
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.error('未找到认证token')
    isExecuting.value = false
    return
  }
  
  // 建立SSE连接
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
  const url = `${baseUrl}/api/v1/ui-automation/executions/${executionId}/stream?token=${encodeURIComponent(token)}`
  appendExecutionOutput(`连接URL: ${url}`)
  
  try {
    currentEventSource = new EventSource(url)
    
    currentEventSource.onopen = (event) => {
      appendExecutionOutput('✅ SSE连接已建立')
      appendExecutionOutput('--- 开始接收实时输出 ---')
      console.log('SSE连接已建立', event)
    }
    
    currentEventSource.onmessage = (event) => {
      console.log('收到SSE消息:', event.data)
      try {
        const data = JSON.parse(event.data)
        handleSSEMessage(data)
      } catch (error) {
        appendExecutionOutput(`解析SSE消息失败: ${event.data}`)
        console.error('解析SSE消息失败:', error)
      }
    }
    
    currentEventSource.onerror = (error) => {
      appendExecutionOutput('❌ SSE连接错误')
      console.error('SSE Error:', error)
      appendExecutionOutput(`连接状态: ${currentEventSource.readyState}`)
      
      if (currentEventSource.readyState === EventSource.CLOSED) {
        appendExecutionOutput('连接已关闭')
      } else if (currentEventSource.readyState === EventSource.CONNECTING) {
        appendExecutionOutput('正在重连...')
      }
      
      isExecuting.value = false
      if (currentEventSource && currentEventSource.readyState === EventSource.CLOSED) {
        currentEventSource = null
      }
    }
  } catch (error) {
    appendExecutionOutput(`创建SSE连接失败: ${error.message}`)
    console.error('创建SSE连接失败:', error)
    isExecuting.value = false
  }
}

// 处理SSE消息
const handleSSEMessage = (data) => {
  const timestamp = new Date().toLocaleTimeString()
  
  switch (data.type) {
    case 'start':
      appendExecutionOutput(`[${timestamp}] ${data.message}`)
      break
    case 'status':
      appendExecutionOutput(`[${timestamp}] 状态: ${data.message}`)
      break
    case 'info':
      appendExecutionOutput(`[${timestamp}] 信息: ${data.message}`)
      break
    case 'command':
      appendExecutionOutput('')
      appendExecutionOutput('--- 执行命令 ---')
      appendExecutionOutput(data.message)
      appendExecutionOutput('')
      break
    case 'stdout':
      appendExecutionOutput(data.message)
      break
    case 'stderr':
      appendExecutionOutput(`🔴 ${data.message}`)
      break
    case 'complete':
      appendExecutionOutput('')
      appendExecutionOutput(`[${timestamp}] ✅ ${data.message}`)
      if (data.returncode !== undefined) {
        appendExecutionOutput(`返回码: ${data.returncode}`)
      }
      isExecuting.value = false
      if (currentEventSource) {
        currentEventSource.close()
        currentEventSource = null
      }
      break
    case 'error':
      appendExecutionOutput('')
      appendExecutionOutput(`[${timestamp}] ❌ ${data.message}`)
      isExecuting.value = false
      if (currentEventSource) {
        currentEventSource.close()
        currentEventSource = null
      }
      break
    default:
      appendExecutionOutput(`[${timestamp}] ${data.message || JSON.stringify(data)}`)
  }
}

// 关闭SSE连接
const closeSSEConnection = () => {
  if (currentEventSource) {
    currentEventSource.close()
    currentEventSource = null
    appendExecutionOutput('SSE连接已关闭')
  }
  // 清理执行ID
  currentExecutionId.value = null
}

// 停止执行
const stopExecution = async () => {
  if (!currentExecutionId.value) {
    ElMessage.warning('没有正在执行的脚本')
    return
  }
  
  try {
    stopping.value = true
    appendExecutionOutput('')
    appendExecutionOutput(`[${new Date().toLocaleTimeString()}] 正在停止执行...`)
    
    const response = await stopUiAutomationExecution(currentExecutionId.value)
    
    if (response && response.data && response.data.success) {
      ElMessage.success('执行已停止')
      appendExecutionOutput(`[${new Date().toLocaleTimeString()}] ✅ 执行已停止`)
      
      // 关闭SSE连接
      closeSSEConnection()
      isExecuting.value = false
    } else {
      ElMessage.error(response?.data?.message || '停止失败')
      appendExecutionOutput(`[${new Date().toLocaleTimeString()}] ❌ 停止失败: ${response?.data?.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('停止执行失败:', error)
    ElMessage.error(`停止执行失败: ${error.message || error}`)
    appendExecutionOutput(`[${new Date().toLocaleTimeString()}] ❌ 停止执行失败: ${error.message || error}`)
  } finally {
    stopping.value = false
  }
}

// 开始调整输出框大小
const startResize = (event) => {
  isResizing.value = true
  const startX = event.clientX
  const startY = event.clientY
  const startWidth = outputWidth.value
  const startHeight = outputHeight.value

  const handleMouseMove = (moveEvent) => {
    if (!isResizing.value) return
    
    const deltaX = moveEvent.clientX - startX
    const deltaY = startY - moveEvent.clientY
    
    const newWidth = Math.max(300, Math.min(1200, startWidth + deltaX))
    const newHeight = Math.max(100, Math.min(600, startHeight + deltaY))
    
    outputWidth.value = newWidth
    outputHeight.value = newHeight
  }

  const handleMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    document.body.style.cursor = ''
    document.body.style.userSelect = ''
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  document.body.style.cursor = 'nw-resize'
  document.body.style.userSelect = 'none'
  event.preventDefault()
}

// 显示生成对话框
const showGenerateDialog = () => {
  generateDialogVisible.value = true
}

// 显示执行选项对话框
const showExecutionOptionsDialog = () => {
  executionOptionsVisible.value = true
}

// 显示帮助对话框
const showHelpDialog = () => {
  helpDialogVisible.value = true
}

// 处理YAML生成
const handleYamlGenerated = (yamlContent) => {
  currentYamlContent.value = yamlContent
  ElMessage.success('YAML脚本已生成')
}

// 查看执行详情
const viewExecution = (execution) => {
  currentExecution.value = execution
  executionDetailVisible.value = true
}



// 查看批次详情
const viewBatch = (batch) => {
  // TODO: 实现批次详情查看
  console.log('查看批次详情:', batch)
}

// 执行批量任务
const executeBatch = (batchData) => {
  // TODO: 实现批量执行
  console.log('执行批量任务:', batchData)
}

// ==================== 辅助方法 ====================

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    active: 'success',
    draft: 'info',
    inactive: 'warning'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    active: '激活',
    draft: '草稿',
    inactive: '停用'
  }
  return texts[status] || status
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}

// ==================== 生命周期 ====================
onMounted(() => {
  loadScripts()
  // 只有在有token的情况下才加载需求
  const token = localStorage.getItem('token')
  if (token) {
    loadRequirements()
  }
  // 初始化高亮
  updateHighlight()
})
</script>

<style lang="scss" scoped>
.ui-automation-page {
  padding: 8px;
  background-color: #f5f7fa;
  height: calc(100vh - 60px);
  font-size: 13px;
  display: flex;
  flex-direction: column;
  
  .compact-tabs {
    background: white;
    border-radius: 6px;
    box-shadow: 0 1px 6px 0 rgba(0, 0, 0, 0.08);
    flex: 1;
    display: flex;
    flex-direction: column;
    
    :deep(.el-tabs__header) {
      margin: 0;
      padding: 0 16px;
      background: #fafbfc;
      border-radius: 6px 6px 0 0;
      border-bottom: 1px solid #e4e7ed;
    }
    
    :deep(.el-tabs__nav-wrap) {
      padding: 8px 0;
    }
    
    :deep(.el-tabs__item) {
      font-size: 13px;
      padding: 0 16px;
      height: 32px;
      line-height: 32px;
    }
    
    :deep(.el-tabs__content) {
      padding: 0;
      flex: 1;
      overflow: hidden;
    }
    
    :deep(.el-tab-pane) {
      height: 100%;
      overflow: hidden;
    }
  }
}

/* 统一接口管理布局 */
.unified-interface-layout {
  display: flex;
  height: 100%;
  overflow: hidden;
  
  .interface-sidebar {
    width: 400px;
    border-right: 1px solid #e4e7ed;
    display: flex;
    flex-direction: column;
    
    .sidebar-header {
      padding: 12px 16px;
      border-bottom: 1px solid #e4e7ed;
      background: #fafbfc;
  display: flex;
  justify-content: space-between;
  align-items: center;
      
      .search-filters {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;
      }
      
      .header-actions {
        display: flex;
        margin-left: 8px;
      }
    }
    
    .interface-list {
      flex: 1;
      overflow-y: auto;
      padding: 8px;
    }
    
    .pagination-small {
      padding: 8px 16px;
      border-top: 1px solid #e4e7ed;
  text-align: center;
    }
  }
  
  .interface-editor {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}

.interface-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f8ff;
  }
  
  .interface-header {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
    
    .interface-name {
      font-weight: 500;
      flex: 1;
      font-size: 13px;
    }
  }
  
  .interface-url {
    color: #666;
    font-size: 12px;
    margin-bottom: 6px;
    word-break: break-all;
  }
  
  .interface-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    color: #999;
    
    .category {
      background: #f0f2f5;
      padding: 2px 6px;
      border-radius: 3px;
    }
  }
}

/* 创建表单样式 */
.create-form {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .form-header {
    padding: 20px 24px 16px 24px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: white;
      display: flex;
      align-items: center;
      gap: 8px;
      
      &::before {
        content: "✨";
    font-size: 16px;
      }
    }
    
    .el-button {
      background: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
      color: white;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
        border-color: rgba(255, 255, 255, 0.5);
      }
    }
  }
  
  .form-content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    background: #fafbfc;
    
    .el-form {
      background: white;
      padding: 24px;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
      max-width: none;
    }
  }
}

/* 脚本编辑器样式 */
.script-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
    color: white;
    border-radius: 8px 8px 0 0;
    margin-bottom: 0;
    
    .script-title {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .name {
    font-size: 16px;
        font-weight: 600;
      }
      
      .el-tag {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;
        font-weight: 500;
      }
    }
    
    .actions {
      display: flex;
      gap: 8px;
      
      .el-button {
        background: rgba(255, 255, 255, 0.2);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;
        font-weight: 500;
        
        &:hover {
          background: rgba(255, 255, 255, 0.3);
          border-color: rgba(255, 255, 255, 0.5);
          transform: translateY(-1px);
        }
        
        &.el-button--danger {
          background: rgba(244, 67, 54, 0.8);
          border-color: rgba(244, 67, 54, 0.8);
          
          &:hover {
            background: rgba(244, 67, 54, 0.9);
            border-color: rgba(244, 67, 54, 0.9);
          }
        }
      }
    }
  }
  
  .yaml-editor-container {
    flex: 1;
    padding: 16px;
    background: #fafbfc;
    
    .yaml-textarea {
      :deep(.el-textarea__inner) {
        font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
        font-size: 13px;
        line-height: 1.4;
        border-radius: 6px;
        border: 1px solid #dcdfe6;
        transition: all 0.2s;
        
        &:focus {
          border-color: #409eff;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
        }
      }
    }
  }
  
  .execution-options {
    padding: 0 16px 16px 16px;
    background: #fafbfc;
    
    :deep(.el-collapse) {
      border: none;
      
      .el-collapse-item__header {
        background: white;
        border: 1px solid #e4e7ed;
        border-radius: 6px 6px 0 0;
        padding: 12px 16px;
        font-weight: 500;
      }
      
      .el-collapse-item__content {
        background: white;
        border: 1px solid #e4e7ed;
        border-top: none;
        border-radius: 0 0 6px 6px;
        padding: 16px;
      }
    }
  }
}

/* 空状态样式 */
.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

/* 悬浮执行输出框样式 */
.floating-execution-output {
  position: fixed;
  z-index: 1000;
  border: 2px solid #409eff;
  border-radius: 8px;
  background: white;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.2);
  resize: both;
  min-width: 300px;
  min-height: 150px;
  max-width: 90vw;
  max-height: 80vh;
  
  .output-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
    cursor: move;
    user-select: none;
    
    .output-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 500;
      color: #409eff;
      
      .el-icon {
        font-size: 16px;
      }
    }
  }
  
  .output-content {
    flex: 1;
    overflow-y: auto;
    height: calc(100% - 60px);
    
    .output-text {
      margin: 0;
      padding: 16px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 12px;
      line-height: 1.6;
      color: #2c3e50;
      background: #f9f9f9;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
    
    .executing-status {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 40px;
      color: #409eff;
      font-size: 14px;
      
      .el-icon {
        font-size: 16px;
      }
    }
  }
  
  .resize-handle {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 16px;
    height: 16px;
    background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
    cursor: nw-resize;
    border-radius: 0 0 6px 0;
    
    &:hover {
      background: linear-gradient(135deg, #66b1ff 0%, #409eff 100%);
    }
    
    &:before,
    &:after {
      content: '';
      position: absolute;
      background: rgba(255, 255, 255, 0.8);
    }
    
    &:before {
      bottom: 2px;
      right: 2px;
      width: 2px;
      height: 10px;
    }
    
    &:after {
      bottom: 2px;
      right: 6px;
      width: 2px;
      height: 6px;
    }
  }
}

/* YAML编辑器样式 */
.yaml-editor-container {
  flex: 1;
  margin: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: white;
  display: flex;
  flex-direction: column;
  min-height: 200px;
  overflow: hidden;
  
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
    border-radius: 6px 6px 0 0;
    
    .editor-title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
    }
    
    .editor-hint {
      font-size: 12px;
      color: #909399;
    }
  }
  
  .yaml-editor-wrapper {
    position: relative;
    flex: 1;
    display: flex;
    min-height: 200px;
    max-height: calc(85vh - 200px);
    overflow: hidden;
    
    .line-numbers {
      width: 50px;
      background: #f8f9fa;
      border-right: 1px solid #e4e7ed;
      overflow: hidden;
      text-align: right;
      padding: 12px 8px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 12px;
      line-height: 1.6;
      color: #409eff;
      user-select: none;
      flex-shrink: 0;
      box-sizing: border-box;
      
      .line-number {
        height: 19.2px; /* 12px * 1.6 line-height */
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    
    .code-area {
      flex: 1;
      position: relative;
    }
    
    .yaml-highlight, .yaml-textarea {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      padding: 12px;
      margin: 0;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 12px;
      line-height: 1.6;
      border: none;
      outline: none;
      resize: none;
      overflow: auto;
      white-space: pre;
      word-wrap: break-word;
      tab-size: 2;
      font-variant-ligatures: none;
      text-rendering: optimizeSpeed;
      -webkit-font-smoothing: subpixel-antialiased;
      max-height: 100%;
      box-sizing: border-box;
    }
    
    .yaml-highlight {
      background-color: #fafbfc;
      color: #2c3e50;
      pointer-events: none;
      z-index: 1;
      font-weight: normal;
      font-style: normal;
      
      /* highlight.js YAML样式 */
      :deep(.hljs-attr) {
        color: #d73a49;
        font-weight: 600;
      }
      
      :deep(.hljs-string) {
        color: #032f62;
      }
      
      :deep(.hljs-number) {
        color: #005cc5;
      }
      
      :deep(.hljs-literal) {
        color: #005cc5;
      }
      
      :deep(.hljs-comment) {
        color: #6a737d;
        font-style: normal;
        opacity: 0.8;
      }
      
      :deep(.hljs-bullet) {
        color: #d73a49;
      }
      
      :deep(.hljs-meta) {
        color: #6f42c1;
      }
    }
    
    .yaml-textarea {
      background: transparent;
      color: transparent;
      caret-color: #409eff;
      z-index: 2;
      
      &:focus {
        outline: 2px solid #409eff;
        outline-offset: -2px;
      }
      
      &::selection {
        background: rgba(64, 158, 255, 0.3);
        color: transparent;
      }
      
      &::placeholder {
        color: #c0c4cc;
      }
    }
  }
}
</style>